package org.cfk.delaytasktutorial.handler;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Component
@RequiredArgsConstructor
public class LazyJobHandler {

    private final ApplicationContext applicationContext;
    private final LazyJobHandlerContent lazyJobHandlerContent;

    public void execute(String worker, String content) throws Exception {
        Method method = lazyJobHandlerContent.getByName(worker);
        if (method == null) {
            throw new IllegalArgumentException("未找到延迟任务处理方法: " + worker);
        }

        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length != 1) {
            throw new IllegalArgumentException("延迟任务处理方法必须只有一个参数");
        }

        Object arg = JSONUtil.toBean(content, parameterTypes[0]);
        Object targetBean = applicationContext.getBean(method.getDeclaringClass());
        method.invoke(targetBean, arg);
    }
}